import { Input, Button, Drawer, Form, Divider, Table, message, Typography, Popconfirm, Modal } from 'antd';
import React, { useState, useContext, useEffect } from 'react';
import { connect, useDispatch } from 'umi';
import styles from '../ActionEdit.less';


const layout = {
  labelCol: { span: 8 },
  wrapperCol: { span: 16 },
};

const EditableCell = ({ editing, dataIndex, title, record, index, children, ...restProps }) => {
  if (editing) {
    if (dataIndex === 'actionCode') {
      return (
        <td {...restProps}>
          <Form.Item
            name={dataIndex}
            style={{
              margin: 0,
            }}
          >
            <Input placeholder="按钮编码" />
          </Form.Item>
        </td>
      );
    }
    if (dataIndex === 'actionName') {
      return (
        <td {...restProps}>
          <Form.Item
            name={dataIndex}
            style={{
              margin: 0,
            }}
          >
            <Input placeholder="按钮名称" />
          </Form.Item>
        </td>
      );
    }
    if (dataIndex === 'sort') {
      return (
        <td {...restProps}>
          <Form.Item
            name={dataIndex}
            style={{
              margin: 0,
            }}
            rules={[{ pattern: /^[1-9][0-9]{0,1}$/g, message: '请输入 1 ~ 99 范围内的正整数' }]}
          >
            <Input placeholder="序号" />
          </Form.Item>
        </td>
      );
    }
  }
  return <td {...restProps}>{children}</td>;
};

const ActionEdit = (props) => {
  const { drawerType, editData, lookDisabled, handleCloseDrawer } = props;
  const [form] = Form.useForm();
  const [formEdit] = Form.useForm();
  const dispatch = useDispatch();
  const [isFirstAddEdit, setIsFirstAddEdit] = useState(false);
  const [actionListData, setActionListData] = useState([]);
  const [editingKey, setEditingKey] = useState('');
  const isEditing = (record) => record.key === editingKey;
  const returnTitle = (type) => {
    if (type === 'add') {
      return '按钮编辑';
    } else if (type === 'edit') {
      return '查询按钮';
    }
    return '查询按钮';
  };

  const components = {
    body: {
      cell: EditableCell,
    },
  };

  const edit = (record) => {
    formEdit.setFieldsValue({
      ...record,
    });
    setEditingKey(record.key);
  };

  const deleteRow = (record) => {
    const newList = actionListData.filter((item) => item !== record);
    setActionListData(newList);
    console.log(record);
    const params = {
      resourceId: editData.resourceId,
      appCode: editData.appCode,
      actionData: {...record},
    };
    curl('resourceActionManageModel/removeResourceAction',params);
  };

  const curl = (url,params) => {
    dispatch({
      type: url,
      payload: params,
    }).then((res) => {
      const { code, message: errMsg } = res;
      if (code === 0) {
        selectActionList();
        setEditingKey('');
      } else {
        message.error(errMsg);
      }
    });
  }

  const selectActionList = () => {
    const paramsData = {
      resourceId: editData.resourceId,
      appCode: editData.appCode,
    };
    dispatch({
      type: 'resourceActionManageModel/selectResourceAction',
      payload: paramsData,
    }).then((res) => {
      if (res.code == 0) {
        setActionListData(res.data.map((d, i) => ({ ...d, key: `key${i}` })));
      }
    });
  };

  useEffect(() => {
    selectActionList();
  }, []);

  const handleSubmit = (key,data) => {
    const editRow = data.find(item => item.key === key);
    if (editRow.actionCode === undefined || editRow.actionCode === '' ||
    editRow.actionName === undefined || editRow.actionName === '') {
      message.warning('按钮编码和按钮名称不能为空！');
      return;
    }
    const params = {
      resourceId: editData.resourceId,
      appCode: editData.appCode,
      actionData: {...editRow},
    };
    curl('resourceActionManageModel/updateResourceAction',params);
  };

  // 新增按钮数据
  const addTableRow = () => {
    if (editingKey) {
      message.warning('存在正在编辑的数据！');
      return;
    }
    const data = {
      key: `new${actionListData.length + 1}`,
      resourceActionId: -1,
      actionId:-1,
      actionCode: undefined,
      actionName: undefined,
      sort: null,
    };
    setActionListData([...actionListData, data]);
    formEdit.setFieldsValue({
      ...data,
    });
    setEditingKey(data.key);
    setIsFirstAddEdit(true);
  };

  const save = (key) => {
    const { validateFields } = formEdit;
    validateFields().then((values) => {
      const newActionDataList = [...actionListData].map((item) => {
        if (item.key === key) {
          return { ...item, actionCode: values.actionCode, actionName: values.actionName,sort: values.sort };
        }
        return item;
      });
      setActionListData(newActionDataList);
      handleSubmit(key,newActionDataList);
    });
  };

  const cancel = () => {
    let newList = [];
    const editData = actionListData.find((d) => d.key === editingKey);
    if (editData.key.indexOf('new') !== -1 && isFirstAddEdit) {
      newList = actionListData.filter((item) => item.key !== editingKey);
      setActionListData(newList);
    }
    setEditingKey('');
    setIsFirstAddEdit(false);
  };

  const columns = [
    {
      title: '按钮编码',
      key: 'actionCode',
      dataIndex: 'actionCode',
      editable: true,
    },
    {
      title: '按钮名称',
      key: 'actionName',
      dataIndex: 'actionName',
      editable: true,
    },
    {
      title: '排序',
      key: 'sort',
      dataIndex: 'sort',
      editable: true,
    },
    {
      title: '操作',
      key: '',
      render: (record) => {
        const editable = isEditing(record);
        const actions = editable ? (
          <span>
            <Typography.Link
              onClick={() => save(record.key)}
              style={{
                marginRight: 8,
              }}
            >
              保存
            </Typography.Link>
            {record.key.indexOf('new') > -1 && (
              <Popconfirm title="确定取消?" onConfirm={cancel}>
                <a>取消</a>
              </Popconfirm>
            )}
          </span>
        ) : (
          <>
            <Typography.Link disabled={editingKey !== ''} onClick={() => edit(record)}>
              编辑
            </Typography.Link>
            &nbsp;&nbsp;&nbsp;
            <Typography.Link disabled={editingKey !== ''} onClick={() => deleteRow(record)}>
              删除
            </Typography.Link>
          </>
        );
        return lookDisabled ? null : actions;
      },
    },
  ];

  const columnsData = columns.map((col) => {
    if (!col.editable) {
      return col;
    }
    return {
      ...col,
      onCell: (record) => ({
        record,
        dataIndex: col.dataIndex,
        title: col.title,
        editing: isEditing(record),
      }),
    };
  });

  return (
    <Drawer
      title={returnTitle(drawerType)}
      width="auto"
      placement="right"
      onClose={handleCloseDrawer}
      visible
      footer={
        <div style={{ textAlign: 'right' }}>
          <Button onClick={handleCloseDrawer} style={{ marginRight: 8 }}>
            取消
          </Button>
        </div>
      }
    >
      <div className={styles.drawerWrapper}>
        <div className={styles.basicInfo}> 基本信息 </div>
        <Form {...layout} form={form} name="nest-messages">
          <Form.Item label="菜单编码" name="resourceCode" initialValue={editData.resourceCode}>
            <Input disabled={true} />
          </Form.Item>
          <Form.Item label="菜单名称" name="resourceName" initialValue={editData.resourceName}>
            <Input disabled={true} />
          </Form.Item>
        </Form>
        <Divider />
        <div className={styles.actionInfo}>
          <span className={styles.actionTitle}>按钮信息</span>
          {lookDisabled ? (
            <span />
          ) : (
            <span className={styles.toggleFont} onClick={addTableRow}>
              新增
            </span>
          )}
        </div>
        <div style={{ display: 'block' }}>
          <Form form={formEdit} component={false}>
            <Table
              rowKey="key"
              components={components}
              columns={columnsData}
              dataSource={actionListData}
              pagination={false}
            />
          </Form>
        </div>
      </div>
    </Drawer>
  );
};

export default connect((state) => state)(ActionEdit);
